package com.ww.springboot.boot.algorithm.leetcode1;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2022-04-22 10:22
 */
public class BU406根据身高重建队列 {

    public static void main(String[] args) {
        int[][] people = {{7, 0}, {4, 4}, {7, 1}, {5, 0}, {6, 1}, {5, 2}};
        int[][] ints = reconstructQueue2(people);
        PrintUtil.print(ints);
    }

    /**
     * 1.先将数组按照身高从高到低排序
     * 最高的k值肯定是0
     * 2.将相同的值按照k值从小到大排序 k小的肯定在前面
     *
     * @param people
     * @return
     */
    public static int[][] reconstructQueue(int[][] people) {
        //1.排序
        Arrays.sort(people, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                return o1[1] - o2[1];
            } else {
                return o2[0] - o1[0];
            }
        });
        PrintUtil.print(people);

        LinkedList<int[]> linkedList = new LinkedList();
        //1.先将最高的排好序
        int max = people[0][0];
        for (int i = 0; i < people.length; i++) {
            if (people[i][0] == max) {
                linkedList.add(i,people[i]);
                continue;
            }
            int k = people[i][1];
            linkedList.add(k,people[i]);
        }

        int[][] arrays = new int[people.length][people[0].length];
        for (int i = 0; i < linkedList.size(); i++) {
            arrays[i] = linkedList.get(i);
        }
        return arrays;
    }


    /**
     * 根据h
     * @param people
     * @return
     */
    public static int[][] reconstructQueue2(int[][] people) {
        Arrays.sort(people, (person1, person2) -> {
            if (person1[0] != person2[0]) {
                return person1[0] - person2[0];
            } else {
                return person2[1] - person1[1];
            }
        });
        int n = people.length;
        int[][] ans = new int[n][];
        for (int[] person : people) {
            int spaces = person[1] + 1;
            for (int i = 0; i < n; ++i) {
                if (ans[i] == null) {
                    --spaces;
                    if (spaces == 0) {
                        ans[i] = person;
                        break;
                    }
                }
            }
        }
        return ans;
    }
}
